package com.example.email.controller;

import com.example.email.entity.Orders;
import com.example.email.service.OrdersService;
import com.example.email.utils.DelayQueue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author wuyunbin
 * @since 2023-04-11
 */
@RestController
@RequestMapping("/orders")
@Slf4j
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("add")
    public String add() {
        log.info("下了订单");
        Orders orders = new Orders();
        ordersService.save(orders);
        //发延时任务-解决付款
        DelayQueue queue=new DelayQueue(redisTemplate,"orders");
        queue.put(orders.getId(),3*60*1000L);
        queue.start();
        return orders.getId();
    }

    @GetMapping("pay/{id}")
    public void pay(@PathVariable String id){
        //修改数据库中的状态
        Orders orders = ordersService.getById(id);
        orders.setStatus("1");
        ordersService.updateById(orders);
        //取消队列里的任务
        DelayQueue queue = new DelayQueue(redisTemplate, "orders");
        queue.cancel(id);
    }

    @GetMapping("send/{id}")
    public String send(@PathVariable String id){
        //打印语句模拟出库
        log.info("订单：{},出库",id);
        //延时1分钟，然后发送邮件到收货人（写死)-后面自行移植到队列中去处理
        List<File> files=new ArrayList<>();
        ordersService.send("617772977@qq.com",
                "测试主题"  ,
                "<a href='http://localhost:8080/orders/check/"+id+"'>确认收货点这里</a>",
                files);

        //发延时任务-解决收货
        DelayQueue queue=new DelayQueue(redisTemplate,"ship");
        queue.put(id,3*60*1000L);
        queue.start();
        return id;
    }

    @GetMapping("check/{id}")
    public String check(@PathVariable String id){
        log.info("订单：{}已确认收货",id);
        return id;
    }

}
